package io.gitee.hefren.hhregistry.health;

import com.google.common.base.Throwables;
import io.gitee.hefren.hhregistry.beans.InstanceMeta;
import io.gitee.hefren.hhregistry.service.RegisterService;
import io.gitee.hefren.hhregistry.service.impl.HhRegisterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Date 2024/5/13
 * @Author lifei
 */
public class HhCheckHealth implements CheckHealth{

    private static final Logger log = LoggerFactory.getLogger(HhCheckHealth.class);

    private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    private final long timeout = 30 * 1000;

    private final RegisterService registerService;

    public HhCheckHealth(RegisterService registerService) {
        this.registerService = registerService;
    }

    @Override
    public void start() {
        executor.scheduleWithFixedDelay(()->{
            try {
                log.debug("==> check health server: {}", HhRegisterService.TIMESTEMPS);
                for (String serverAndInstance : HhRegisterService.TIMESTEMPS.keySet()) {
                    long diffTime = System.currentTimeMillis() - HhRegisterService.TIMESTEMPS.get(serverAndInstance);
                    log.debug("==> check health serverAndInstance: {}, diffTime: {}", serverAndInstance, diffTime);
                    if (diffTime > timeout) {
                        int index = serverAndInstance.indexOf("@");
                        String server = serverAndInstance.substring(0, index);
                        String url = serverAndInstance.substring(index + 1);
                        InstanceMeta instanceMeta = InstanceMeta.fromUrl(url);
                        log.debug("===> ***unregister server: {}, instanceMeta: {}", server, instanceMeta);
                        registerService.unregister(server, instanceMeta);
                        HhRegisterService.TIMESTEMPS.remove(serverAndInstance);
                    }
                }
            }catch (Exception e) {
                log.error(Throwables.getStackTraceAsString(e));
            }
        }, 10, 10, TimeUnit.SECONDS);
    }

    @Override
    public void stop() {
        executor.shutdown();
    }
}
